<template>
	<ComIndex ref="commonIndexRef" :isInitList="false" v-model:keywords="keywords" @search="handleSearch" :init-api="false">
		<template #filterForm>
			<ComFilterForm :searchList="searchList"></ComFilterForm>
		</template>
		<template #search>
			<Search :showSearch="true" v-model="keywords">
				<template #right>
					<div>
						<a-button @click="handleAdd">新建</a-button>
						<a-button status="danger" @click="delList" :disabled="!selectedKeys?.length">删除</a-button>
					</div>
				</template>
			</Search>
		</template>
		<div class="base-padding h100">
			<ComTable
				row-key="id"
				v-model:pageForm="pageForm"
				@page-change="getList"
				:row-selection="rowSelection"
				v-model:selectedKeys="selectedKeys"
				:loading="loading"
				@update="handleUpdate"
				:pagination="{ total }"
				:columns="titleList"
				:data="dataList"
				column-resizable
				page-position="bottom"
			>
				<template #custom="{ item }">
					<a-table-column v-bind="item" ellipsis :title="item.title" :data-index="String(item.field)" :width="getWidth(item.field, item.fieldType)">
						<template #cell="{ record, column, rowIndex }">
							<div class="column-item">
								<template v-if="item.field === isKeyInfo.id">
									<ComLink v-if="record?.id" :labelShort="record[isKeyInfo.id]?.labelShort" :text="record[item.field]?.value" @click="handleDetail(record, item)" />
									<FieldText
										v-else
										v-model="record.value"
										:name="isKeyInfo?.name"
										:border="false"
										@change="handleUpdate(record)"
										hiddenLabel
										style="width: 100%; padding: 0; min-height: auto"
									></FieldText>
								</template>
								<div v-else class="flex column-field" @click="record[item.field].status = 'edit'">
									<template v-if="record?.[item.field]">
										<component
											size="mini"
											style="padding: 0px; min-height: auto; width: 100%"
											hiddenLabel
											:hiddenEditIcon="false"
											:arcoProps="{
												'checked-value': '1',
												'unchecked-value': '0'
											}"
											v-model="record[item.field].fieldValue"
											v-model:fieldShow="record[item.field].fieldShow"
											v-model:extra="record[item.field].extra"
											:tag="SelectInfo(showFieldList, item?.fieldType, 'tag')"
											:prop="item?.prop"
											:fieldType="SelectInfo(showFieldList, item?.fieldType, 'fieldType')"
											:status="record[item.field].status || 'view'"
											:is="SelectInfo(showFieldList, item?.fieldType, 'component')"
											:options="item?.options"
											@keyup.enter="handleEdit(record, item.field)"
											:border="false"
											@change="handleEdit(record, item.field)"
											@out-click="setFieldStatus(record[item.field])"
										></component>
										<div class="edit-icon" v-if="record[item.field].status === 'view'" >
											<icon-pen-fill />
										</div>
									</template>
								</div>
							</div>
						</template>
					</a-table-column>
				</template>
			</ComTable>
		</div>
	</ComIndex>
</template>
<script lang="ts" setup>
import { customerDataPage, columnTitle, customerDataUpdate, dataDelete } from "@/api/customerManage/customer";
import { customerDataSubmit } from "@/api/customerManage/customer";
import ComIndex from "@/components/ComIndex/Index.vue";
import { useMessage } from "@/hooks/useMessage";
import ComTable from "@/components/ComTable/ComTable.vue";
import ComLink from "@/components/ComLink.vue";
import { useShowFieldList } from "@/utils/field";
import { SelectInfo } from "@/utils/index";
import { useI18n } from "@/hooks/useI18n";
import ComFilterForm from "./components/ComFilterForm.vue";

const { wsCache } = useCache();
const searchForm = ref([]);
const keywords = ref("");
const selectedKeys = ref([]);
const rowSelection = reactive({
	type: "checkbox",
	showCheckedAll: true,
	onlyCurrent: false
});
const { t } = useI18n();
const showFieldList = useShowFieldList();
const message = useMessage();
const commonIndexRef: any = ref(null);
const router = useRouter();
const route = useRoute();
const titleList: any = ref([]);
const isKeyInfo = ref({});

const bizId = ref(1);

const getWidth = (id, type) => {
	if (isKeyInfo.value.id === id) return 270;
	return SelectInfo(showFieldList, type, "width", "value") || 150;
};
const getTitle = async () => {
	if (!bizId.value) return;
	try {
		loading.value = true;
		const data = await columnTitle({
			bizId: bizId.value
		});
		isKeyInfo.value = data.find((i) => i.isKey) || {};
		const arr = data.map((i) => {
			return {
				...i?.extraObject,
				...i,
				title: i.name,
				slotName: i.id + ".parm",
				field: i.id,
				prop: getProp(i),
				options: getOptions(i) //单选多选的时候
			};
		});
		titleList.value = arr;
		await getList();
	} catch (error) {
	} finally {
		loading.value = false;
	}
};

const handleSearch = (data) => {
	const list = data.filter((i) => i.filterType === "field");
	searchForm.value = list.map((i) => {
		return {
			key: i.filterIndex,
			value: i.value,
			queryType: i.queryType
		};
	});
	getList();
};

const getOptions = (item) => {
	if ([5, 6].includes(item.fieldType)) {
		return item.values;
	} else if ([16].includes(item.fieldType)) {
		return item.relations;
	}
};

const searchList = computed(() => {
	const arr = titleList.value.map((i) => {
		return {
			label: i?.title,
			value: "",
			options: i?.options,
			prop: i?.prop,
			id: i?.id,
			queryType: SelectInfo(showFieldList, i?.fieldType, "queryType"),
			fieldType: i.fieldType
		};
	});
	return arr;
});

const handleUpdate = async (data) => {
	await customerDataSubmit({
		bizId: bizId.value,
		columnList: [
			{
				fieldConfig: isKeyInfo.value.id,
				fieldShow: data.value,
				fieldValue: data.value
			}
		]
	});
	getList();
};

const handleEdit = async (info, key) => {
	try {
		loading.value = true;
		handleUpdateStatus(info);
		const arr = getRecordData(info);
		await customerDataUpdate({
			mainId: info.id,
			columnList: arr
		});
		message.success(t("base.saveSuccess"));
		getList();
	} catch (error) {
	} finally {
		loading.value = false;
	}
};

const chooseRow = ref({});
const handleUpdateStatus = (record) => {
	if (chooseRow.value.id && chooseRow.value.id !== record.id) {
		setStatus(chooseRow.value);
	}
	chooseRow.value = record;
};

const setStatus = (obj) => {
	for (let i in obj) {
		if (isNumericKey(i)) {
			// 点击其他行的时候 关闭其他行的编辑状态
			setFieldStatus(obj[i]);
			obj[i].fieldShow = obj[i].parm || obj[i].value;
			obj[i].fieldValue = obj[i].value;
			obj[i].extra = obj[i].extraObject || {};
		}
	}
};

const setFieldStatus = (info) => {
	if (info?.config?.fieldType === 3) {
		info.status = "edit";
	} else {
		info.status = "view";
	}
};
function isNumericKey(key) {
	return !Number.isNaN(Number(key));
}

const getRecordData = (data) => {
	let arr: any = [];
	for (let i in data) {
		if (isNumericKey(i)) {
			arr.push({
				fieldConfig: i,
				id: data[i].columnId,
				fieldShow: data[i].fieldShow,
				fieldValue: data[i].fieldValue,
				extra: data[i].extra ? JSON.stringify(data[i].extra) : null
			});
		}
	}
	return arr;
};
const getProp = (item) => {
	let obj = {
		ico: item.ico,
		name: item.name
	};
	obj = { ...obj, ...item.extraObject };
	return obj;
};
const dataList = ref([]);
const loading = ref(false);
const total = ref(0);
const pageForm = ref({});
const getList = async () => {
	try {
		loading.value = true;
		const data = await customerDataPage({
			bizId: bizId.value,
			...pageForm.value,
			querys: searchForm.value,
			keywords: keywords.value
		});
		if (Array.isArray(data.list)) {
			data.list.forEach((i) => {
				setStatus(i);
			});
		}
		dataList.value = data.list;
		total.value = data.total;
	} catch (error) {
	} finally {
		loading.value = false;
	}
};

const handleDetail = (row, item) => {
	router.push({
		path: "/addCustomer",
		query: {
			bizId: bizId.value,
			id: row.id
		}
	});
};
watch(
	() => route,
	() => {
		const data = route.params;
		bizId.value = Number(data.id) >= 1 ? data.id : wsCache.get("menuId");
		if (data.id == "0") {
			router.push({ path: `/customer/${bizId.value}` });
		} else {
			getTitle();
		}
	},
	{ immediate: true, deep: true }
);

const handleAdd = () => {
	dataList.value.unshift({});
};
const delList = async () => {
	await message.delConfirm();
	await dataDelete({
		mainIds: selectedKeys.value.join(",")
	});
	getList();
};
</script>

<style scoped lang="scss">
.column-field {
	display: flex;
	width: 100%;
	gap: 4px;
	align-items: center;
	justify-content: space-between;
	&:hover {
		.edit-icon {
			opacity: 1;
		}
	}
	.edit-icon {
		color: #9999b1;
		// font-size: 12px;
		opacity: 0;
		cursor: pointer;
		padding: 4px;
		line-height: 1;
		border-radius: 4px;
		&:hover {
			background-color: #f2f2f2;
		}
	}
}
</style>
